package softswitch.service;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Circuit;
import softswitch.model.Package;
import softswitch.model.PackageSummary;


@Stateless
public class PackageSummaryService {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public PackageSummary getById(Integer id){	
		return em.find(PackageSummary.class, id);
	}
    
    public PackageSummary save(PackageSummary packagesummary) {
    	em.persist(packagesummary); 
    	return packagesummary;
    }
    
    public PackageSummary update(PackageSummary packagesummary) {
    	return em.merge(packagesummary); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(PackageSummary.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<PackageSummary> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM PackageSummary e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //----------------------------------------------------------------------
	
	public void deleteByMonth(Integer year, Integer month, Circuit circuit) {
		String sql = "DELETE FROM PackageSummary e WHERE e.year=:year AND  e.month=:month ";
		if(circuit!=null){
			sql = sql + " AND e.circuit=:circuit ";
		}
		Query query = em.createQuery(sql);
		query.setParameter("year", year);
		query.setParameter("month", month);
		if(circuit!=null){
			query.setParameter("circuit", circuit);
		}
        query.executeUpdate();        
    }
	
	public PackageSummary getByDate(Package packag, Date calldate) {
		PackageSummary result = null;
		Query query = em.createQuery("SELECT e FROM PackageSummary e WHERE e.packag=:packag AND e.calldate=:calldate");
		query.setParameter("packag", packag);
		query.setParameter("calldate", calldate);
		try {
			result = (PackageSummary) query.getSingleResult(); 
        }
    	catch (Exception e) {
			//e.printStackTrace();
		}
        return result;
    }
	



	
}

